package com.example.datadashboard.service.impl;

import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.datadashboard.dto.PageResultDTO;
import com.example.datadashboard.dto.UserDTO;
import com.example.datadashboard.dto.UserQueryDTO;
import com.example.datadashboard.entity.User;
import com.example.datadashboard.mapper.UserMapper;
import com.example.datadashboard.service.UserService;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public PageResultDTO<UserDTO> queryUsers(UserQueryDTO queryDTO) {
        // 分页查询用户
        QueryWrapper<User> wrapper = generatQueryWrapper(queryDTO);
        Page<User> page = page(new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize()), wrapper);

        List<UserDTO> dtos = page.getRecords().stream().map(u -> {
            UserDTO dto = new UserDTO();
            dto.setId(u.getId());
            dto.setUsername(u.getUsername());
            dto.setIdNumber(u.getIdNumber());
            dto.setPhone(u.getPhone());
            dto.setEmail(u.getEmail());
            dto.setStatus(u.getStatus());
            dto.setCreateTime(u.getCreateTime() != null ? u.getCreateTime().toString() : null);
            dto.setUpdateTime(u.getUpdateTime() != null ? u.getUpdateTime().toString() : null);
            dto.setSexy(u.getSexy());
            dto.setAddress(u.getAddress());
            dto.setRemark(u.getRemark());
            return dto;
        }).collect(Collectors.toList());

        PageResultDTO<UserDTO> result = new PageResultDTO<>();
        result.setTotal(page.getTotal());
        result.setRecords(dtos);
        return result;
    }

    @Override
    public void exportUsers(HttpServletResponse response, UserQueryDTO queryDTO) {
        QueryWrapper<User> wrapper = generatQueryWrapper(queryDTO);
        // 导出所有匹配用户
        List<User> list = list(wrapper);
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=\"users.csv\"");
        try (PrintWriter writer = response.getWriter()) {
            writer.println("id,用户名,身份证号,电话,电子邮箱,状态,创建时间,更新时间,性别,联系地址,备注");
            for (User u : list) {
                writer.println(String.format(
                    "%d,%s,%s,%s,%s,%d,%s,%s,%d,%s,%s",
                    u.getId(),
                    u.getUsername(),
                    u.getIdNumber(),
                    u.getPhone(),
                    u.getEmail(),
                    u.getStatus(),
                    u.getCreateTime() != null ? u.getCreateTime().toString() : "",
                    u.getUpdateTime() != null ? u.getUpdateTime().toString() : "",
                    u.getSexy(),
                    u.getAddress() != null ? u.getAddress() : "",
                    u.getRemark() != null ? u.getRemark() : ""
                ));
            }
        } catch (IOException e) {
            throw new RuntimeException("导出用户数据失败", e);
        }
    }

    private QueryWrapper<User> generatQueryWrapper(UserQueryDTO queryDTO){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(queryDTO.getUsername()), "username", queryDTO.getUsername());
        wrapper.like(StringUtils.isNoneBlank(queryDTO.getIdNumber()), "id_number", queryDTO.getIdNumber());
        wrapper.like(StringUtils.isNoneBlank(queryDTO.getPhone()), "phone", queryDTO.getPhone());
        return wrapper ;
    }
}